package service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import model.Item;

/**
 * Session Bean implementation class Catalog
 */
@Stateless
public class Catalog implements CatalogRemote {

	@PersistenceContext(unitName = "catalogunit")
	private EntityManager entityManager = null;

    public Catalog() {
    }

    public List<Item> getItems(int firstItem, int batchSize) {
        if (firstItem < 0) {
            firstItem = 0;
        }
      /*
        if (batchSize < 0 || batchSize > 50) {
            batchSize = 10;
        }*/
        Query q = entityManager.createQuery("select object(o) from Item as o");
        q.setMaxResults(batchSize);
        q.setFirstResult(firstItem);
        return q.getResultList();

    }

    public Item getItem(String id) {
        Item o = (Item) entityManager.find(Item.class, id);
        return o;
    }
    
  
    
	public Item create() {
		Item newb = new Item();
		newb.setName("noname");
		newb.setDescription("..");
		newb.setProductid(0);
		newb.setPrice(0.0);
		entityManager.persist(newb);
		return newb;
	}    
    
	public Item save(Item item) {
		entityManager.merge(item);
		return item;
	}    
    

    public int getItemCount() {
        int count = ((Long) entityManager.createQuery("select count(o) from Item as o").getSingleResult()).intValue();
        return count;
    }

}
